import hashlib
import math
import time
import requests
import random
from colorama import Fore, Back, Style
import configparser
import os

import sys
import os
import signal
import json

# pyinstaller --add-data 'config.ini:.' main.py --name '麻溜'
# 获取当前脚本所在的目录
script_dir = os.path.dirname(os.path.abspath(__file__))
config = configparser.ConfigParser()
# 获取 INI 文件路径
if getattr(sys, 'frozen', False):
    # 打包后的运行环境
    ini_path = os.path.join(sys._MEIPASS, "config.ini")
else:
    # 开发环境
    ini_path = os.path.join(script_dir, "config.ini")

config.read(ini_path)


def getTimeStamp():
    # node = execjs.get()
    # with open('./temp/01.js', encoding='utf-8') as f:
    #     js_code = f.read()
    # ctx = node.compile(js_code, cwd=r'./temp/node_modules')
    # sign = ctx.call("getTime")
    return int(time.time() * 1000) + 5000 + random.randint(1, 1000)


class QianQu:
    def __init__(self, utoken, uid, cangid, sleep):
        # copy Fssetch请求
        headers = {
            "method": "POST",
            "authority": "app.szyqg.cloud",
            "scheme": "https",
            "pragma": "no-cache",
            "cache-control": "no-cache",
            "sec-ch-ua": '"Google Chrome";v="113", "Chromium";v="113", "Not-A.Brand";v="24"',
            "sec-ch-ua-platform": '"Android"',
            "sec-ch-ua-mobile": "?1",
            "user-agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Mobile Safari/537.36",
            "content-type": "application/x-www-form-urlencoded",
            "accept": "*/*",
            "origin": "https://qg.app.blwapp.com",
            "sec-fetch-site": "cross-site",
            "sec-fetch-mode": "cors",
            "sec-fetch-dest": "empty",
            "referer": "https://qg.app.blwapp.com/",
            "accept-encoding": "gzip, deflate, br",
            "accept-language": "zh-CN,zh;q=0.9"
        }
        self.headers = headers
        self.uid = uid
        self.cangid = cangid
        self.utoken = utoken
        self.apiKey = 'qugoushenghuo20230405..'
        # 获取当前进程 ID
        self.session = requests.session()
        self.session.headers = self.headers
        # 设置 默认绿色积分
        self.lvsejifen = 2000

    def getUserInfo(self):
        urlStr = "userindexgetuserinfo"
        # 处理时间戳
        timestamp = getTimeStamp()
        # timestamp = 1686147753530
        # 模拟发送请求
        url = "https://app.szyqg.cloud/api/index.php?c=user&a=index&do=getuserinfo"
        data = {
            'timestamp': timestamp,
            'uid': self.uid,
            'utoken': self.utoken,
        }

        # web 逆向加密
        r = ''.join([str(v) for v in data.values()])
        r = self.apiKey + r + urlStr
        sign = hashlib.md5(r.encode('utf-8')).hexdigest()
        data['Sign'] = sign
        # print(2,json.dumps(data))  //这里的意思是以 json 方式提交 默认self.session.post 会以表单形式提交
        self.session.headers["Authortoken"] = sign
        response = self.session.post(url, data=data).json()
        # 向下取整 如果大于 2000 默认设置 2000
        self.lvsejifen = min(math.floor(response["data"]["lvsejifen"]), 2000)
        # TODO 后期做邮件推送 小语 10

        # 处理响应的内容
        print('设置积分为:', self.lvsejifen, '接口返回积分为:', response["data"]["lvsejifen"])

    def getGameDetail(self):
        urlStr = "indexmaichangcanyu"
        # 处理时间戳
        timestamp = getTimeStamp()
        # timestamp = 1686147753530
        # 加密请求

        # 模拟发送请求
        url = "https://app.szyqg.cloud/api/index.php?c=index&a=maichang&do=canyu"
        data = {
            "cangid": self.cangid,
            "chiid": "87",
            "jifen": self.lvsejifen,
            "paypsd": "",
            'timestamp': timestamp,
            'uid': self.uid,
            'utoken': self.utoken,
        }

        # web 逆向加密
        r = ''.join([str(v) for v in data.values()])
        r = self.apiKey + r + urlStr
        sign = hashlib.md5(r.encode('utf-8')).hexdigest()
        # print(r, 12312)
        data['Sign'] = sign

        # print(data)
        # print(2,json.dumps(data))  //这里的意思是以 json 方式提交 默认self.session.post 会以表单形式提交
        self.session.headers["Authortoken"] = sign
        response = self.session.post(url, data=data).json()
        # 处理响应的内容
        print(response, 123)


if __name__ == '__main__':
    # 获取参数
    utoken = config.get('DEFAULT', 'utoken')
    uid = config.get('DEFAULT', 'uid')
    sleep = config.getfloat('DEFAULT', 'sleep')
    cangid = config.get('DEFAULT', 'cangid')

    bigQianqu = QianQu(utoken, uid, cangid, sleep)
    do_operations = True


    def operations():
        global do_operations
        while do_operations:
            # print(Fore.RED + '这段文字将会是红色的。' + Style.RESET_ALL )

            user_input = input(
                f'{Fore.BLUE}麻溜请输入{Style.RESET_ALL} \n 1 执行脚本 \n 2 初始化配置 \n 3 查看配置 \n {Fore.RED}说明:ctrl+enter 停止执行, 初始化配置填入要修改的,不需要修改直接回车{Style.RESET_ALL}')
            if user_input == "1":
                # 死循环
                while do_operations:
                    try:
                        bigQianqu.getUserInfo()
                        bigQianqu.getGameDetail()
                        # 马骝在这里改下请求时间,单位是秒
                        # time.sleep(300)
                        print('start')
                        time.sleep(sleep)  # 100ms的意思  这里简洁 .1 === 0.1
                    except Exception as e:
                        do_operations = False
                        print(f"发生了一个错误{e},参数错误请请联系马骝!")
            if user_input == "2":
                # 从命令行获取用户输入
                lutoken = input("请输入utoken：")
                luid = input("请输入uid：")
                lsleep = input("请输入休眠时间（秒）：")
                lcangid = input("请输入期数：")

                # 将用户输入写入config.ini文件
                config.set('DEFAULT', 'utoken', lutoken or config.get('DEFAULT', 'utoken'))
                config.set('DEFAULT', 'uid', luid or config.get('DEFAULT', 'uid'))
                config.set('DEFAULT', 'sleep', lsleep or config.get('DEFAULT', 'sleep'))
                config.set('DEFAULT', 'cangid', lcangid or config.get('DEFAULT', 'cangid'))

                with open(ini_path, 'w') as f:
                    config.write(f)
                # 关闭文件，保存更改
                # with open(ini_path, 'r') as configfile:
                #     print(configfile.read())
                # os.execv(sys.executable, ['python'] + sys.argv)
            if user_input == "3":
                # 将新生成的配置文件读取出来并打印出来
                with open(ini_path, 'r') as configfile:
                    print(configfile.read())


    try:
        operations()
        do_operations = False
    except KeyboardInterrupt:
        print("\n程序已停止运行")
